package com.itheima.reggie.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.SecureUtil;
import com.itheima.reggie.common.Constant;
import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.domain.Employee;
import com.itheima.reggie.mapper.EmployeeMapper;
import com.itheima.reggie.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;


//员工管理模块
@Service
@Transactional
public class EmployeeServiceImpl implements EmployeeService {


    @Autowired
    private EmployeeMapper employeeMapper;



    //员工登录
    @Override
    public ResultInfo login(String username, String password) {
        //1.根据username查询mapper
        Employee employee = employeeMapper.findByUsername(username);
        if (employee==null) {
            return ResultInfo.error("此用户明不存在");
        }
        //2.密码比较
        String md5 = SecureUtil.md5(password);  //将明文->md5加密
        if (!StrUtil.equals(md5,employee.getPassword())) {
            return ResultInfo.error("密码错误");
        }
        //3.判断账号是否禁用
        if (employee.getStatus()==0) {
            return ResultInfo.error("此账号被禁用,请联系管理员");
        }
        //4.登陆成功,返回结果
        return ResultInfo.success(employee);
    }


    //员工列表
    @Override
    public List<Employee> findList(String name) {
        //调用mapper查询
        return employeeMapper.findList(name);
    }

    //新增员工
    @Override
    public void save(Employee employee) {
        //1.补全员工信息
        //1-1 使用雪花的id生成器
        long id = IdUtil.getSnowflake(1,1).nextId();
        employee.setId(id);
        //1-2 初始密码
        String pwd = SecureUtil.md5(Constant.INIT_PASSWORD);
        employee.setPassword(pwd);
        //1-3 员工状态
        employee.setStatus(Employee.STATUS_ENABLE);
        //1-4 创建,更新时间
        // employee.setCreateTime(new Date());  //todo 暂时写死
        // employee.setUpdateTime(new Date());
        // //1-5 创建,更新人
        // employee.setCreateUser(1L);    //todo 暂时写死
        // employee.setUpdateUser(1L);
        //2.调用mapper添加
        employeeMapper.save(employee);

    }

    @Override
    public Employee findById(long id) {
        //直接mapper查询
        return employeeMapper.findById(id);

    }


    //修改员工
    @Override
    public void updateById(Employee employee) {
        //1.设置操作人和时间
        //employee.setUpdateUser(1L);  //todo 暂时写死
        //employee.setUpdateTime(new Date());
        //调用mapper修改
        employeeMapper.updateById(employee);
    }
}
